package com.pyb.controller;

import com.pyb.model.Student;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class StudentController extends HttpServlet {
    private List<Student> students = new ArrayList<>();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求编码为 UTF-8（仅对 POST 请求有效）
        request.setCharacterEncoding("UTF-8");
        // 设置响应内容类型和编码
        response.setContentType("text/html;charset=UTF-8");

        String action = request.getParameter("action");

        if (action == null) {
            response.sendRedirect("index.jsp");
            return;
        }

        switch (action) {
            case "add":
                addStudent(request, response);
                break;
            case "list":
                listStudents(request, response);
                break;
            case "edit":
                showEditForm(request, response);
                break;
            case "update":
                updateStudent(request, response);
                break;
            case "delete":
                deleteStudent(request, response);
                break;
            default:
                response.sendRedirect("index.jsp");
        }
    }

    private void addStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        int age;
        try {
            age = Integer.parseInt(request.getParameter("age"));
        } catch (NumberFormatException e) {
            System.out.println("年龄格式错误: " + e.getMessage());
            response.sendRedirect("index.jsp");
            return;
        }

        students.add(new Student(id, name, age));
        response.sendRedirect("student?action=list");
    }

    private void listStudents(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("students", students);
        request.getRequestDispatcher("/listStudents.jsp").forward(request, response);
    }

    private void showEditForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String rawId = request.getParameter("id");
        if (rawId == null || rawId.trim().isEmpty()) {
            System.out.println("ID 为空");
            response.sendRedirect("student?action=list");
            return;
        }

        String id = decodeParameter(rawId);

        Student student = students.stream()
                .filter(s -> s.getId().equals(id))
                .findFirst()
                .orElse(null);

        if (student == null) {
            System.out.println("未找到对应的学生");
            response.sendRedirect("student?action=list");
            return;
        }

        request.setAttribute("student", student);
        request.getRequestDispatcher("/editStudent.jsp").forward(request, response);
    }

    private void updateStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String rawId = request.getParameter("id");
        String name = request.getParameter("name");
        int age;
        try {
            age = Integer.parseInt(request.getParameter("age"));
        } catch (NumberFormatException e) {
            System.out.println("年龄格式错误: " + e.getMessage());
            response.sendRedirect("student?action=list");
            return;
        }

        if (rawId == null || rawId.trim().isEmpty()) {
            System.out.println("ID 为空");
            response.sendRedirect("student?action=list");
            return;
        }

        String id = decodeParameter(rawId);

        students.stream()
                .filter(s -> s.getId().equals(id))
                .findFirst()
                .ifPresent(student -> {
                    student.setName(name);
                    student.setAge(age);
                });

        response.sendRedirect("student?action=list");
    }

    private void deleteStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String rawId = request.getParameter("id");
        if (rawId == null || rawId.trim().isEmpty()) {
            System.out.println("ID 为空");
            response.sendRedirect("student?action=list");
            return;
        }

        String id = decodeParameter(rawId);

        boolean removed = students.removeIf(s -> s.getId().equals(id));
        if (!removed) {
            System.out.println("未找到要删除的学生");
        }

        response.sendRedirect("student?action=list");
    }

    /**
     * 解码 GET 请求参数中的中文字符（适用于 Tomcat 默认 ISO-8859-1）
     */
    private String decodeParameter(String param) {
        try {
            return new String(param.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        } catch (Exception e) {
            System.err.println("解码失败: " + e.getMessage());
            return param; // 返回原始值作为降级处理
        }
    }
}